package com.ccepc.algmanage.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.util.Collections;

@Slf4j
public class ApiRequestUtils {
    // 发送请求的方法
    private static ResponseEntity<Object> sendRequest(String url, HttpEntity<?> requestEntity) {
        // 创建RestTemplate
        RestTemplate restTemplate = new RestTemplate();
        // 发送请求
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
        // 处理响应
        if (response.getStatusCode().is2xxSuccessful()) {
            String responseBody = response.getBody();
            log.info("成功响应：" + responseBody);
            return ResponseEntity.ok(CommonUtils.stringToJson(responseBody));
        } else {
            log.error("请求失败，HTTP 状态码：" + response.getStatusCode());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }

    public static ResponseEntity<Object> postData(String url, String jsonRequestBody) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        // 封装请求体和请求头
        HttpEntity<String> requestEntity = new HttpEntity<>(jsonRequestBody, headers);
        return sendRequest(url, requestEntity);
    }

    public static ResponseEntity<Object> postFormData(String url, MultiValueMap<String, Object> formData) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        // 封装请求体和请求头
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(formData, headers);
        return sendRequest(url, requestEntity);
    }

}
